<?php
namespace Admin\Mobile\Controllers;


use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\msg\XhmsgRecord;
use Admin\Models\sys\XhsysUserSetting;
use Admin\Models\user\XhsysUser;
use Bpm\Models\XHBpmPlanContent;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Phalcon\Di;
use Services\App;

class IndexController extends ControllerBase
{


    private static $enums = [
        'iNoType' => [1 => '通知', 2 => '公告'],
    ];
    private static $homeTags = ['pClass','msg','notice'];
    private static $backLogTags = ['planContent','useCar','applyTab'];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Page Not Found']);
    }

    /**
     * 主界面
     *
     * created by dale 2017/10/27
     */
    public function indexAction()
    {
        Assets::flexSlider2();
        Assets::easyUIMobile();
        Assets::sweetAlert2();
        $this->view->pick('index/index');
        Assets::importJs('js/index/index.js');
    }

    /**
     * Home界面
     *
     * created by dale 2017/9/13
     */
    public function HomeAction()
    {
        Assets::easyUIMobile();
        Assets::flexSlider2();
        $this->view->pick('index/home');
        Assets::importJs('js/index/home.js');
        $this->view->setVars([
            'homeMap' =>  $this->getHomeMap(),
        ]);

    }

    


    /**
     * 登录界面
     *
     * @return bool
     * created by dale 2017/10/27
     */
    public function loginAction()
    {
        try{
            $backUrl = $this->request->getQuery('backUrl','string');
            $url = $backUrl ?: 'mobile/index/index';
            if(User::isLogin()){ //刷新页面
                return $this->response->redirect($url);
            }
            if($this->cookies->has("remember")
                &&  $this->cookies->has("account")
                &&  $this->cookies->has("password")
                &&  $this->cookies->get("remember") == 'true'
                &&  $this->cookies->get("account") != 'admin'){
                User::login($this->cookies->get("account"),base64_decode($this->cookies->get("password")));
                return $this->response->redirect($url);
            }
        }catch (\Exception $e){
            $this->cookies->get('password')->delete();
        }
        Assets::clipboard();
        Assets::easyUIMobile();
        Assets::sweetAlert2();
        $this->view->pick('index/login');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/index/login.js');

        if($this->cookies->has("account")){
            $account = $this->cookies->get('account')->getValue();
        }else{
            $account = '';
        }
        if($this->cookies->has("password") && $this->cookies->has("remember") && $this->cookies->get("remember") != 'false' ){
            $password = $this->cookies->get('password')->getValue();
        }else{
            $password = '';
        }
        if ($this->cookies->has('remember')) {
            $this->view->setVar('remember',$this->cookies->get('remember')->getValue());
        } else {
            $this->view->setVar('remember',true);
        }
        if ($this->cookies->has('trust')) {
            $this->view->setVar('trust',$this->cookies->get('trust')->getValue());
        } else {
            $this->view->setVar('trust',false);
        }
        $this->view->setVars([
            'account'=>$account,
            'password'=>base64_decode($password),
        ]);
        return true;
    }

    /**
     * 登录操作
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171027
     * modify by dale 20171220
     *
     */
    public function doLoginAction(){
        try{
            $password  = base64_encode($this->request->getPost('password'));
            $account   = $this->request->getPost('account');
            $remember  = $this->request->getPost('remember');
            $smsCode   = $this->request->getPost('smsCode');
            $trust     = $this->request->getPost('trust','string');
            $sMobileId = $this->request->getPost('sMobileId','string');
            $this->cookies->set('account',$account,time() + 365* 86400);
            $this->cookies->set('password',$password,time() + 365 * 86400);
            $this->cookies->set('remember',$remember,time() + 365 * 86400, '/', null,  null, true);
            $this->cookies->set('trust',$trust,time() + 365 * 86400, '/', null,  null, true);
            $user = $this->modelsManager->createBuilder()
                ->columns(['u.iUserId', 'u.sLogonName', 'u.sUserName', 'u.iUserType', 'u.sLogonPwd', 'u.sSelfPhone', 'u.iSchoolId'])
                ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\hrm\\XhhrmStaff', 'u.iUserId = s.iUserId AND s.bDelete = 0', 's')
                ->where('u.bDelete = 0 AND u.bDisable = 0')
                ->andWhere('u.sLogonName = :account: OR u.sSelfPhone = :account:', ['account' => $account])
                ->orderBy('s.iStaffId DESC,u.iUserId ASC')
                ->limit(1)
                ->getQuery()->execute()->toArray();
            if (!$user) {
                return $this->sendErrorResponse(500, '没有找到该用户');
            }
            $user = $user[0];
            $setting = XhsysUserSetting::find([
                'columns'    => 'id,userId,content',
                'conditions' => 'bDelete = 0 and target = :target: and userId = :userId: ',
                'bind'       => ['target' => 'MOBILE_UUID' , 'userId' => $user['iUserId']]
            ])->toArray();
            $extensions = array_column($setting, 'content');
            $needSmsCode = $sMobileId ?  in_array($sMobileId, $extensions) : false ; //判断是否信任设备
            User::login($account,base64_decode($password),$smsCode, $needSmsCode); //登录
            if ($trust == 'true' && $sMobileId) { //更新人力表里面的uuid
                if (!$needSmsCode) {
                    $obj = new XhsysUserSetting();
                    $obj->userId = $user['iUserId'];
                    $obj->target = 'MOBILE_UUID';
                    $obj->content = $sMobileId;
                    $obj->extra = serialize([
                        'ip' => Tool::getIp()
                    ]);
                    if (!$obj->save()) {
                        $this->praseLog(500, '保存手机设备号失败', '保存手机设备号失败');
                    }
                }
            }
//            else if ($trust == 'false' && $sMobileId) {
//                if (trim($staff->sMobileId) == trim($sMobileId)) {
//                    $staff->sMobileId = '';
//                    if (!$staff->save()) {
//                        $this->praseLog(500, '删除信任设备失败', '删除信任设备失败');
//                    }
//                }

//            }
            return $this->sendSuccessResponse('登录成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }




    /**
     * 代办
     * created by dale 2017/10/23
     */
    public function backlogAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('index/backlog');
        Assets::importJs('js/index/backlog.js');
        $this->view->setVars([
            'backLogMaps'=> $this->getbackLogMap()
        ]);
    }


    /**
     * 快捷键
     * created by dale 2017/10/26
     */
    public function shortcutAction(){
        Assets::easyUIMobile();
        Assets::flexSlider2();
        $this->view->pick('index/shortcut');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/index/shortcut.js');
    }


    /**
     * 系统
     * created by dale 2017/10/25
     */
    public function systemAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('index/system');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/index/system.js');
    }


    /**
     * 我的
     * created by dale 2017/10/23
     */
    public function mineAction()
    {
        $userId=Main::getLoginUserInfo('userId');
        Assets::easyUIMobile();
        $this->view->pick('index/mine');
        Assets::importJs('js/index/mine.js');
        $userName=Main::getLoginUserInfo('userName');
        $staff=XhhrmStaff::findFirst([
            'conditions'=>'bDelete=0 AND iUserId=:iUserId:',
            'bind'=>['iUserId'=>$userId],
        ]);
        if(!$staff){
            $name = $userName;
            $dep = '';
        }else{
            $name = $staff->sStaffName;
            $dep = XhhrmDepart::getDepName($staff->sDepIds);
        }
        $this->view->setVars([
            'name'=>$name,
            'dep' =>$dep,
        ]);
    }


    public function getBannerAction(){
        $banners = Main::getConfigByName('moblie')['banner'];
        if(count(json_decode($banners)) == 0){
            return $this->sendErrorResponse(400,'缺少配置项');
        }
        return $banners;
    }


    /**
     * 获取最新的字段
     *
     * @param $table
     * @param $targetFields  ['id','time']
     * @return mixed
     * @throws \Exception
     *
     * create by dale 20180233
     */
    public function findLatestField($table,$targetFields){
        try{
            if(is_string($targetFields)){
                $sql = "select {$targetFields} from {$table}  ORDER BY {$targetFields} DESC ";
                return $this->db->fetchOne($sql)[$targetFields];
            }
            if(is_array($targetFields)){
                $arr = [];
                foreach ($targetFields as $key => $field){
                    $arr[$key] = $this->db->fetchOne("select {$field} from {$table}  ORDER BY {$field} DESC")[$field];
                }
                return $arr;
            }

        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取首页的map
     *
     * @return string
     * create by dale 20180233
     */
    public function getHomeMap(){
        $tags      = self::$homeTags;
        $mapValues = $this->getMapTable();
        $maps = [];
        foreach ($tags as $tag) {
            $tableInfo = $mapValues[$tag];
            $arr = $this->findLatestField($tableInfo[0],[0=>$tableInfo[1],1=>$tableInfo[2]]);
            $maps[] = ['tag' => $tag , 'yesId'=>$arr[0] ,'yesDate' =>$arr[1] ];
        }
        return json_encode($maps);
    }

    /**
     * 获取待办的映射
     *
     * create by dale 20180233
     */
    public function getbackLogMap(){
        $tags      = self::$backLogTags;
        $mapValues = $this->getMapTable();
        $maps = [];
        foreach ($tags as $tag){
            $tableInfo = $mapValues[$tag];
            $arr = $this->findLatestField($tableInfo[0],[0=>$tableInfo[1],1=>$tableInfo[2]]);
            $maps[] = ['tag' => $tag , 'yesId'=>$arr[0] ,'yesDate' =>$arr[1] ];
        }
        return json_encode($maps);
    }


    /**
     * 数据库映射
     *
     * @return array
     * create by dale 20180233
     */
    public function getMapTable(){
        return [
            'pClass' => ['XHSchool_PublicClass','iPCId','tLastModifyDate'],
            'msg'    => ['XHRes_Article','iArtId','tLastModifyDate'],
            'notice' => ['XHMsg_Notice','iNoId','tLastModifyDate'],
            'planContent'=> ['XHBpm_PlanContent','iBPCId','tLastModifyDate'],
            'useCar' => ['XHLm_UseCar','iUCId','tLastModifyDate'],
            'applyTab' => ['XHIms_ApplyTablet','iRTId','tLastModifyDate']
        ];
    }


    public function ajaxCheckUpdateAction(){
        $maps    = $this->request->getPost('maps');
        $module  = $this->request->getPost('module','int');
        $flag    = $this->checkUpdate($maps,$module);

        return $this->sendJsonResponse(['flag'=>$flag ]);
    }

    /**
     * 是否更新界面操作
     *
     * @param $maps [ 0=> ['tag'=> 'pClass' ,'yesId'=>'','yesDate'=>], ]
     * @param $module  1=> 新增  2=>时间更新  3=>新增和更新
     * @return bool
     *
     * create by dale 20180233
     */
    public function checkUpdate($maps,$module=3){
        $flag = false;
        $mapValues = $this->getMapTable();
        switch ($module){
            case 1 :
                foreach ($maps as $map){
                    $tableInfo = $mapValues[$map['tag']];
                    $flag =$this->findLatestField($tableInfo[0],$tableInfo[1]) > $map['yesId'] ? true :false;
                    if($flag){
                        break;
                    }
                }
                break;
            case 2 :
                foreach ($maps as $map){
                    $tableInfo = $mapValues[$map['tag']];
                    $flag = strtotime($this->findLatestField($tableInfo[0],$tableInfo[2])) > strtotime($map['yesDate']) ? true :false;
                    if($flag){
                        break;
                    }
                }
                break;
            case 3 :
                foreach ($maps as $map){
                    $tableInfo = $mapValues[$map['tag']];
                    $flag = ($this->findLatestField($tableInfo[0],$tableInfo[1]) > $map['yesId'] ? true :false )
                    OR (strtotime($this->findLatestField($tableInfo[0],$tableInfo[2])) > strtotime($map['yesDate']) ? true :false);
                    if($flag){
                        break;
                    }
                }
                break;
        }
        return $flag;
    }

    /**
     * 判断是否需要手机验证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180809
     */
    public function checkNeedValidAction()
    {
        $account = $this->request->getPost('account', 'string');
        $sMobileId = $this->request->getPost('sMobileId','string');
        $trust = $this->request->getPost('trust','string');
        if (!$account) {
            return $this->sendErrorResponse(400, '账号不能为空',  false);
        }
        //判断是否信任
        if ($sMobileId && $trust == 'true') {
//            return $this->response->setJsonContent(json_encode(['trust' => $trust, 'id' => $sMobileId]), JSON_UNESCAPED_UNICODE);
            $sql = "select e.id,e.userId,e.content from  XHSys_UserSetting as e left join XHSys_User as u on u.iUserId = e.userId  where e.bDelete = 0 and e.target = 'MOBILE_UUID' and  ( u.sLogonName = '{$account}' or u.sSelfPhone = '{$account}'  ) ";
            $extensions = array_values(array_filter(array_column($this->db->fetchAll($sql), 'content')));
            if (in_array($sMobileId, $extensions)) {
                return $this->response->setStatusCode(400)->setJsonContent(['code' => 400, 'msg' => '无需发送短信'], JSON_UNESCAPED_UNICODE);
            }
        }
        $sysConfig = Main::getConfigByName('admin');

        //判断是否需要发送验证码登陆
        if ($account == 'admin') {
            $phone = Tool::getValue($sysConfig, 'phone');
            if ($phone) {
                return $this->response->setStatusCode(200)->setJsonContent(['code' => 200, 'msg' => '需发送短信'], JSON_UNESCAPED_UNICODE);
            }
        }
        else {
            $user = $this->modelsManager->createBuilder()
                ->columns(['u.iUserId', 'u.sLogonName', 'u.sUserName', 'u.iUserType', 'u.sLogonPwd', 'u.sSelfPhone', 'u.iSchoolId'])
                ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\hrm\\XhhrmStaff', 'u.iUserId = s.iUserId AND s.bDelete = 0', 's')
                ->where('u.bDelete = 0 AND u.bDisable = 0')
                ->andWhere('u.sLogonName = :account: OR u.sSelfPhone = :account:', ['account' => $account])
                ->orderBy('s.iStaffId DESC,u.iUserId ASC')
                ->limit(1)
                ->getQuery()->execute()->toArray();
            if (!$user) {
                return $this->response->setStatusCode(400)->setJsonContent(['code' => 400, 'msg' => '无该账号'], JSON_UNESCAPED_UNICODE);
            }
            $user = $user[0];

            try {
                $depInfo = Hrm::getDepInfoByUser($user['iUserId']);
            }
            catch (\Exception $e){
                $depInfo = [];
            }
            $needSmsCodeDep = Tool::getValue($sysConfig, 'needSmsCodeDep', [], function ($value) {
                return array_filter(explode('|', $value));
            });

            $checkDep = array_intersect($needSmsCodeDep, array_column($depInfo, 'tag'))
                || $needSmsCodeDep[0] == 'all';
            if ($checkDep && $user['sSelfPhone']) {
                return $this->response->setStatusCode(200)->setJsonContent(['code' => 200, 'msg' => '需发送短信'], JSON_UNESCAPED_UNICODE);
            }
        }
        return $this->response->setStatusCode(400)->setJsonContent(['code' => 400, 'msg' => '无需发送短信'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取版本号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180829
     */
    public function checkVersionAction(){
        try {
            $data = $this->request->getPost();
            if (isset($data['packageName']) && $data['packageName'] ){
                $info = App::getAppInfoByPackage($data['packageName']);
                if ($info['name'] == $data['name']) {
                    $version = App::getAppInfoById($info['appId'], 1);
                    $version = $version['appVersions'];
//                    return $this->sendJsonResponse($data);
                    $version = Tool::getValue($version, 0, []);
                    if ($version['versionCode'] <= $data['versionCode'] && $version['versionName'] <= $data['versionName']){
                        return $this->response->setStatusCode(200)
                            ->setJsonContent(['code'=> 200, 'msg' => '已更新至最新版'], JSON_UNESCAPED_UNICODE);
                    } else {
                        if (Tool::getValue($data, 'isios', null)) {
                            return $this->response->setStatusCode(200)
                                ->setJsonContent(['code'=> 201,'msg' => '请更新到最新版本','url' => $version['url'] ], JSON_UNESCAPED_UNICODE);
                        } else {
                            return $this->response->setStatusCode(200)
                                ->setJsonContent(['code'=> 201,'msg' => '请更新到最新版本','url' => "itms-services://?action=download-manifest&url=".$version['plistUrl'] ], JSON_UNESCAPED_UNICODE);
                        }
                    }
                }
            }
            return $this->response->setStatusCode(500)
                ->setJsonContent(['code' => 500, '未比对到相应版本'], JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof \Helpers\XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * base64test
     *
     * create by dale  20181030
     */
    public function testAction()
    {
        $this->view->pick('index/test');
        $base = '';
        $this->view->setVars([
            'src' => $base,
        ]);
    }


}

